﻿using System;
using System.Collections.Concurrent;
using System.Windows.Threading;
using WPFCommon.ViewModels.Base;
using WPFCommon.ViewModels.Logger;

namespace WPFCommon.ViewModels.Popup
{
    public class PopupLogger : ViewModelBase
    {
        #region private fields

        private TimeSpan _logFrequency;
        private bool _logStarted;
        private ConcurrentQueue<PopupViewModel> _popupQueue = new ConcurrentQueue<PopupViewModel>();
        private PopupViewModel _popupViewModel;
        private bool _popupDisplaying;

        #endregion

        #region prop

        public bool PopupDisplaying
        {
            get => _popupDisplaying;
            set
            {
                _popupDisplaying = value;
                OnPropertyChanged();
            }
        }

        public PopupViewModel PopupViewModel
        {
            get => _popupViewModel;
           private set
            {
                _popupViewModel = value;
                OnPropertyChanged();
            }
        }

        #endregion

        #region ctor

        public PopupLogger(TimeSpan logFrequency)
        {
            _logFrequency = logFrequency;
        }

        #endregion

        #region api

        public void StartLogging()
        {
            if(_logStarted) throw new InvalidOperationException("Can not start logging twice");
            _logStarted = true;
            
            var timer = new DispatcherTimer()
            {
                Interval = _logFrequency, IsEnabled = true
            };
            timer.Tick += ConsumeLoggingQueue;
        }

        public void EnqueuePopup(PopupViewModel popupViewModel)
        {
            _popupQueue.Enqueue(popupViewModel);
        }
        

        #endregion
        /// <summary>
        /// Take the oldest message from queue and log if allowed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ConsumeLoggingQueue(object sender, EventArgs e)
        {
            if (PopupDisplaying) return;
            var popupAvailable = _popupQueue.TryDequeue(out var popupViewModel);
            if (!popupAvailable) return;

            PopupDisplaying = true;
            PopupViewModel = popupViewModel;

        }
    }
}